﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Community.IMode;
using System.IO;
using FantastPlatform.Framework.Core;
using FantastPlatform.Community.Model;
using Yaxunsoft.CasesManagement;
using System.Data.SqlClient;
using System.Configuration;

namespace FantastPlatform.Community.UI.Service
{
    public partial class CaseCallBackService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            ICaseCallBackService service = ServiceFactory.CreateService<ICaseCallBackService>();
            ConditionGroup group = new ConditionGroup();
            group.Conditions.Add(new Condition { Field = "Enable", Type = typeof(bool).FullName, Value1 = true });
            switch (Action)
            {
                case "Upload":
                    string name = string.Empty;
                    string savePath = string.Empty;
                    if (Request.Files.Count > 0)
                    {
                        HttpPostedFile postedFile = Request.Files[0];
                        name = postedFile.FileName;
                        int index = name.LastIndexOf('.');
                        int nameIndex = name.LastIndexOf("\\") + 1;
                        string fileName = name.Substring(nameIndex, name.Length - nameIndex);
                        string extName = name.Substring(index, name.Length - index);
                        if (!extName.Equals(".png") && !extName.Equals(".jpg") && !extName.Equals(".bmp"))
                        {
                            ReturnErrorMessage("上传失败，上传图片的格式必须为png,jpg,bmp中的一种");
                        }
                        //try
                        //{
                        //    System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
                        //    //if (image.Width != 48 && image.Height != 48)
                        //    //{
                        //    //    ReturnErrorMessage("上传失败，上传图片的大小必须为48*48");
                        //    //}
                        //}
                        //catch
                        //{
                        //    throw new Exception("上传失败，请检查文件是否合法");
                        //}
                        string filePath = "../upload/" + DateTime.Now.Year.ToString() + "/";
                        savePath = Server.MapPath(filePath);
                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }
                        filePath += DateTime.Now.Month.ToString() + "/";
                        savePath += DateTime.Now.Month.ToString() + "/";
                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }
                        string id = Guid.NewGuid().ToString();
                        //fileName =  extName;
                        savePath += fileName;
                        //检查是否在服务器上已经存在用户上传的同名文件
                        if (File.Exists(savePath))
                        {
                            File.Delete(savePath);
                        }
                        postedFile.SaveAs(savePath);
                        int total = 0;

                        //ICaseCallBack caseCallBack = new CaseCallBack();

                        //caseCallBack.CaseId = Id;
                        //caseCallBack.ImageUrl = savePath;
                        //service.Create(caseCallBack);
                        ReturnSuccessMessage(filePath+fileName);
                    }
                    break;
                case "Add":
                    string data = Data;
                    if (String.IsNullOrEmpty(data))
                    {
                        throw new Exception("传入的数据为空");
                    }
                    ICaseCallBack caseCallBack2 = (ICaseCallBack)JsonToEntity<CaseCallBack>(RepairString(data));
                    int totalCount = 0;

                    ICaseCallBack callBack = service.GetCaseCallBackByCaseId(caseCallBack2.CaseId);
                    if (callBack == null)
                    {
                        // caseCallBack2.CaseId = Id;
                        service.Create(caseCallBack2);
                        UpdateCaseMainLin(caseCallBack2.CaseId);
                        ReturnSuccessMessage("案件回访保存成功");
                    }
                    else
                    {
                        //增加判断，在更新时是否重新上传图片，重新上传图片则进行旧图片的删除。
                        //  ICaseCallBack caseCallBackOld = service.Get(caseCallBack2.Id);
                        if (!callBack.ImageUrl.Equals(caseCallBack2.ImageUrl))
                        {
                            //以下删除旧图片功能于2009/09/07增加 By杨雄
                            //找到未更新前的警种图片，并删除
                            string imgname = callBack.ImageUrl;
                            string imgurl = Server.MapPath("../upload/") + imgname;
                            if (File.Exists(imgurl))
                            {
                                File.Delete(imgurl);
                            }
                        }
                        callBack.ImageUrl = caseCallBack2.ImageUrl;
                        callBack.Description = caseCallBack2.Description;
                        service.Update(callBack); 
                        UpdateCaseMainLin(caseCallBack2.CaseId);
                        ReturnSuccessMessage("案件回访更新成功");
                    }
                    break;

                case "Get":
                    ICaseCallBack callBack2 = service.GetCaseCallBackByCaseId(Id);
                    if (callBack2 == null)
                    {
                        callBack2 = new CaseCallBack();
                    }
                    ReturnObj(callBack2);
                    break;
            }
        }

        private void UpdateCaseMainLin(int Id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CaseManagement"].ConnectionString))
            {
                conn.Open(); 
                using (SqlCommand cmd = new SqlCommand("UPDATE [Case].[dbo].[CaseMainLine]  SET   [IsCallBack] = 1 WHERE Id = '" + Id + "'", conn))
                {                                       
                    cmd.ExecuteNonQuery();
                }
                conn.Close(); 
            }
            
        }
    }
}